package elastic


import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/olivere/elastic/v7"
)

type Person struct {
	HostName    string `json:"hostname"`
	IpAddr     string    `json:"ipaddr"`
	LogContent string   `json:"logcontent"`
	Updated_at string `json:"updated_at"`
}
var Client *elastic.Client

func InitElastic(url string) {

	var err error	//这个地方有个小坑 不加上elastic.setsniff(false) 会连接不上
	Client, err = elastic.NewClient(elastic.SetSniff(false), elastic.SetURL(url))
	if err != nil {
		fmt.Println("Connect to es failed!")
		panic(err)
	}

	fmt.Println("Connect to es success!")

}

func IndexElastic(hostname,ipaddr,logline string)  {
	p1 := Person{HostName: hostname, IpAddr: ipaddr, LogContent: logline ,Updated_at: time.Now().Format("2006/01/02 15:04:05")}
	put1, err := Client.Index().
		Index("logbase").
		BodyJson(p1).
		Do(context.Background())
	if err != nil {
		// Handle error
		panic(err)
	}
	log.Printf("Indexed  %s to index 【 %s 】, type %s\n", put1.Id, put1.Index, put1.Type)
}